<?php
/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @copyright Copyright 2008 Rodrigo Rutkoski Rodrigues
 */

global $php_errno;

$php_errno = array(
  1     => 'E_ERROR', 
  2     => 'E_WARNING', 
  4     => 'E_PARSE', 
  8     => 'E_NOTICE', 
  16    => 'E_CORE_ERROR', 
  32    => 'E_CORE_WARNING', 
  64    => 'E_COMPILE_ERROR', 
  128   => 'E_COMPILE_WARNING',
  256   => 'E_USER_ERROR', 
  512   => 'E_USER_WARNING', 
  1024  => 'E_USER_NOTICE', 
  2048  => 'E_STRICT', 
  4096  => 'E_RECOVERABLE_ERROR', 
  8192  => 'E_DEPRECATED', 
  16384 => 'E_USER_DEPRECATED',
  30719 => 'E_ALL'
);

function sy_exception_handler($e)
{
  sy_log('exception', array($e->getMessage(), $e->getTraceAsString(), $e->getFile() . ' (' . $e->getLine() . ')'));

  if (SY_DEBUG_ENABLED) {
    if (Simplify::getRequest() && Simplify::getRequest()->isAjax()) {
      $exc = array(
        'exception' => array(
          'message' => $e->getMessage(),
          'trace' => $e->getTraceAsString(),
          'file' => $e->getFile(),
          'line' => $e->getLine()
        )
      );

      ob_end_clean();

      header('Content-type: application/json; charset="utf-8"');

      echo json_encode($exc);
    } else {
      pre($e->getMessage());
      pre($e->getTraceAsString());
      pre($e->getFile() . ' - ' . $e->getLine());
    }
  }
}

function sy_log($file, $data, $lines = 300)
{
  static $logs;

  if (empty($logs)) $logs = array();

  if (! Simplify::getConfig()) return;

  $file = Simplify::getConfig()->get('app_dir') . '/logs/' . $file . '.log';

  $a = @file($file, FILE_IGNORE_NEW_LINES);
  if ($lines && count($a) > $lines) {
    $a = array_slice($a, count($a) - $lines);
  }

  if (! isset($logs[$file])) {
    $logs[$file] = true;
    $a[] = "-> started " . date('Y-m-d H:i:s');
  }

  $output = date('Y-m-d H:i:s') . ' -> ';

  if (is_string($data)) {
    $output .= trim($data);
  } elseif (is_a($data, 'IDictionary')) {
    $data = $data->getAll();
    array_walk_recursive($data, 'sy_array_map');
    $output .= var_export($data, true);
  } else {
    $output .= var_export($data, true);
  }

  $a[] = $output;

  file_put_contents($file, implode("\n", $a));
}

function fatal_error_handler($buffer)
{
  if (ereg("(.*error</b>:.+)(<br)", $buffer, $regs)) {
    $ajax = Simplify::getRequest() && Simplify::getRequest()->isAjax();

    $err = strip_tags(preg_replace("/<.*?>/","", $regs[1]));

    if ($ajax) {
      sy_log('buffer', $buffer);

      header('Content-type: application/json; charset="utf-8"');
      $buffer = json_encode(array('errors' => $err));
    } else {
      $buffer = $err;
    }

    sy_log('fatal_error', $err);
  }

  return $buffer;
}

function error_handler($errno, $errstr, $errfile, $errline)
{
  global $php_errno;

  //if (! in_array($errno, array(E_STRICT, E_DEPRECATED, E_WARNING, E_NOTICE))) {
  if ($errno & error_reporting()) {
    $err = sprintf('%s: %s in %s on line %d', $php_errno[$errno], $errstr, $errfile, $errline);

    if (Simplify::getRequest() && Simplify::getRequest()->isAjax()) {
      header('Content-type: application/json; charset="utf-8"');
      echo json_encode(array('errors' => $err));
    } else {
      echo $err;
    }

    sy_log('error', $err);

    ob_flush();

    die();
  } else {
    return false;
  }
}

sy_define_once('SY_DEBUG_ENABLED', false);

foreach ($php_errno as $no=>$err) {
  sy_define_once($err, $no);
}

if (SY_DEBUG_ENABLED) {
  error_reporting(E_ALL ^ (E_NOTICE));
  ini_set('display_errors', 1);
  ob_start("fatal_error_handler");
  set_error_handler("error_handler");
  set_exception_handler('sy_exception_handler');
} else {
  error_reporting(E_NONE);
  ini_set('display_errors', 0);
}

?>